//订单
(function() {
	var db = require("../db/index");
	var config = require("../_include/config");
	var db_table_name = config.dbname.ach;
	var db_id_prefix = config.dbIdPrefix.ach;
	var helper = require("../_include/helper");
	var midEvent = require("../../middleware/index");
	var _uuid = 0;

	//构造函数
	var _con = function(info, is_for_cash_com) { //is_for_cash_com为ture时，作为单纯计算订单价格的状态
		console.log("ACHINFO:", info);
		var self = this;
		do {
			//订单编号
			// self._id = "A_" + Math.random().toString(32).substr(2) + (_uuid++).toString(32); // + (+new Date).toString(16);
			//改用纯数字
			self._id = (new Date).format("yyyyMMdd") + Math.random().toFixed(8).substr(2); // + (+new Date).toString(16);
		} while (db.find_by_id(db_table_name, self._id));
		//订单详情
		self.info = {};

		//初始化订单状态，必须在最前面，不然后面的订单状态可能因此无法修改
		self.info.state = _con.STATE.未确认;

		//用户信息
		var user = UserCon.get(info.user_id);
		if (!user) {
			throwCusError("找不到指定用户")
		}
		self.info.user_id = info.user_id;

		var bus_id = info.bus_id;
		if (!bus_id) {
			bus_id = goods.bus_id;
		}
		bus = BusCon.get(bus_id);
		if (!bus) {
			throw "找不到指定商家";
		}
		self.info.bus_id = bus_id;


		self.info.use_space = !!info.use_space;
		if (info.use_space) {

			//消费所使用的空间，比如餐饮业中的餐桌信息
			var space = self.info.space_id && BusSpaceCon.get(self.info.space_id);
			self._updateSpace(space);

		} else {

			//收货地址
			if (info.user_address_id) {
				var user_address = user.getOneAddress(info.user_address_id);
			} else {
				user_address = user.getDefaultAddress();
			}
			self._updateUserAddress(user_address);
		}

		//快递单号
		self.info.express_id = info.express_id;

		//将商品以及优惠信息进行缓存，确保能够回到当时的交易场景
		var goods_info = info.goods_info || [];
		var goods;
		self.info.goods_info = goods_info.map(function(goods_id_and_num) {
			goods = GoodsCon.get(goods_id_and_num.goods_id);
			var num = ~~goods_id_and_num.num || 1;
			if (!is_for_cash_com) {
				//从库存里面减去售出的数量
				goods._cutNum(num);
			}
			return {
				//将商品信息进行缓存
				goods: $Object.clone(goods),
				buffs: $Object.clone(goods.getBuffsDetail()),
				num: num
			};
		});

		//初始化BUFF信息
		self.info.buffs = info.buffs || [];
		//是否禁止货到付款
		self.info.is_only_online_pay = self.isOnlyOlinePay();
		// 支付方式，默认是“货到付款”//“担保交易”
		var pay_method = info.pay_method || _con.METHOD.货到付款;
		if (self.info.is_only_online_pay && pay_method == _con.METHOD.货到付款) {
			pay_method = _con.METHOD.担保交易
		}
		self.info.pay_method = pay_method;

		// //导购者
		// var guide_id = info.guide_id;
		// self.info.guide_id = guide_id;
		// if (guide_id) {
		// 	var guide = BusGuideCon.get(guide_id); //.getDetail();
		// 	if (guide && guide.user_id !== info.user_id) {
		// 		var guide_buff = bus.getGuideConfigBuff();
		// 		console.log("订单通过导购链接而来，触发商家导购链接BUFF", guide_buff);
		// 		self._addBuffByInstance(guide_buff);
		// 	}
		// }

		// //推荐者，在订单完成后才有返利
		// var recommender_id = info.recommender_id
		// if (guide && guide.user_id === recommender_id) { //如果导购者和推荐者是同一个人的话，只用导购
		// 	recommender_id && console.log("导购链接和推荐链接的人是同一个");
		// } else {
		// 	self.info.recommender_id = recommender_id;
		// 	if (recommender_id && recommender_id !== info.user_id /*推荐者与购买者不可同一个人*/ ) {
		// 		var recommender = UserCon.get(recommender_id);
		// 		if (!recommender) {
		// 			throw "找不到指定推荐者";
		// 		} else { //有相关的推荐者，就要加上商家的推荐返利功能
		// 			var recommend_buff = bus.getRecommendConfigBuff();
		// 			console.log("订单通过推荐而下，触发商家推荐返利BUFF", recommend_buff)
		// 			self._addBuffByInstance(recommend_buff);
		// 		}
		// 	}
		// }


		//推荐者和导购者合并成同一个人，只能触发一个
		var recommender_id = info.recommender_id;
		self.info.recommender_id = recommender_id;
		if (recommender_id && recommender_id !== info.user_id /*推荐者与购买者不可同一个人*/ ) {
			var recommender = UserCon.get(recommender_id);
			if (!recommender) {
				// throw "找不到指定推荐者";
				console.error("找不到指定推荐者");
				self.info.recommender_id = null;
			} else { //有相关的推荐者，就要加上商家的推荐返利功能
				var recommend_buff = bus.getRecommendConfigBuff();
				console.log("订单通过推荐而下，触发商家推荐返利BUFF", recommend_buff)
				self._addBuffByInstance(recommend_buff);
			}
		}

		//自定义物流的记录点
		self.info.transportation_point = [];

		//最终的花费=原人民币额度*BUFF，暂不不计算，可能有BUFFS加入。
		self.cash = 0;

		//原额度花费，在不计算本身BUFF时候（info.buff）
		self.sou_cash = 0;

		//自定义价格
		self.cus_cash = 0;

		self.create_time = +new Date;

		//使用推荐返利的钱抵扣
		// self.bind_acc

		//使用账户金额的前抵扣
		// self.bus_user_money

		if (!is_for_cash_com) {
			db.insert(db_table_name, self);
			console.log("生成了一个订单：", info.user_id, self.info.user_address, self.info.buffs);
		}

	};
	//技能
	module.exports = _con;
	_con.prototype = require("./skill");
	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		if (result) {
			result.__proto__ = _con.prototype;
			//判定时间，自动确认收货
			if (result.info.shipment_time && (config.autoConfirmFinishedAchTimeOut + result.info.shipment_time > +new Date)) {
				if (result.info.state === _con.STATE.ol未收货) {
					//自动完结订单，走完流程
					// var bus = BusCon.get(this.info.bus_id);
					// bus.state_ach_ol未发货_to_ol未收货({
					// 	ach_id: Id
					// });
					var user = UserCon.get(this.info.user_id);
					user.state_ach_ol未收货_to_ol交易完成(Id)
				} else if (result.info.state === _con.STATE.已发货) {
					var user = UserCon.get(this.info.user_id);
					user.state_ach_已发货_to_未收货未付款(Id);
					var bus = BusCon.get(this.info.bus_id)
					bus.state_ach_未收货未付款_to_交易完成(Id);
				}
			}
		}
		return result;
	};
	//订单状态枚举，按流程排列
	_con.STATE = {
		"未确认": -1,
		//在线付款，旧版，不再使用
		"未付款": 0,
		"已付款": 1,
		"运货中": 2,
		"确认收货": 3,
		"未评价": 4,
		"已经评价": 5,
		//在线支付
		"ol未付款": 11,
		"ol未发货": 12,
		"ol未收货": 13,
		"ol交易完成": 14,
		"ol已评价": 15,
		//货到付款
		"未发货": 20,
		"已发货": 21,
		"未收货未付款": 22, //货物已经送达，等待用户接货并付款
		"交易完成": 23,
		"已评价": 24,
		//当面付款
		"face未付款": 30,
		"face交易完成": 31, //确认付款，用户无需任何操作即可完成
		"face已评价": 32
	};
	_con.METHOD = {
		"担保交易": "partner_trade_by_buyer", //默认交易方式
		// "即时到账":"direct_pay_by_user",
		"货到付款": "payment_in_cash",
		"财付通担保交易": "partner_tenpay",
		"支付宝网页支付": "alipay.wap.auth.authAndExecute",
		"微信支付": "weixin_pay",
		"当面付款": "face_pay",
	};
	var BusCon = require("../bus/_con");
	var UserCon = require("../user/_con");
	var UserAddressCon = require("../user_address/_con");
	var BusGuideCon = require("../bus.guide/_con");
	var BusSpaceCon = require("../bus.space/_con");
	var GoodsCon = require("../goods/_con");
	var $Object = require("../_include/$.Object");
	var midEvent = require("../../middleware/index");
	var config = require("../_include/config");

}());